//当前预览的文档封面ID 引用 titleimg然后读取
var current_titleimg_catid = 0;
var _catid = 0;
//当前列表的分类ID
var catid = 0;
//当前文章的分类ID
var artid = 0;
//上传图片弹窗控件
var uploadImgBox = $("#upload_imgbox");
//封面图展示框
var showTitleImgBox = $('#show_titleimg');
//封面图展示框 loading
var showTitleImgBoxLoading = null;
//当前文章ID
var flag = false;
//编辑器对象
var editor = null;
//全局主框架高度
var height = $(window).height() - 55;
$(".widget-box").css("margin", 0);
uploadImgBox.find('.close').click(function () {
    uploadImgBox.hide();
});
uploadImgBox.find('.btn-success').click(function () {
    uploadImgBox.hide();
});
$('.book-titleimg').click(function () {
    current_titleimg_catid = parseInt($(this).attr('catid').replace("catid-titleimg-", ''));
    if (current_titleimg_catid === 0) {
        return layer.msg('请点击图片封面', {shift: 6});
    }
    showTitleImgBox.find('img').attr('src', $(this).attr('imgurl'));
    showTitleImgBox.find('.close,.btn-success').click(function () {
        closeShowTitleBox();
    });
    showTitleImgBox.show();
    showTitleImgBox.find('.btn-info').click(function () {
        uploadImgBox.find('iframe').attr('src', UPLOAD_SERVER_URL + '&catid=' + current_titleimg_catid + '&callback=callback_titleimg');
        // uploadImgBox.show(); /关闭弹窗扔到上传页面
        //添加loading
        showTitleImgBoxLoading = layer.load(1, {shade: false});
    });
    return false;
});


editor = editormd("markdown", {
    saveHTMLToTextarea: true,
    width: "100%",
    height: height,
    markdown: "",
    path: LIB_PATH,
    dialogLockScreen : true,   // 设置弹出层对话框不锁屏，全局通用，默认为 true
    dialogShowMask : true,     // 设置弹出层对话框显示透明遮罩层，全局通用，默认为 true
    dialogDraggable : true,    // 设置弹出层对话框不可拖动，全局通用，默认为 true
    dialogMaskOpacity : 0.4,    // 设置透明遮罩层的透明度，全局通用，默认值为 0.1
    dialogMaskBgColor : "#000", // 设置透明遮罩层的背景颜色，全局通用，默认为 #fff
    imageUpload : true,     //开启图片对话框的上传功能
    imageFormats : ["jpg", "jpeg", "gif", "png"],
    imageUploadURL : UPLOAD_SERVER_URL + '&from=editor',    //上传地址
    toolbarIcons: function () {
        return [
            "bold", "del", "italic", "quote", "|",
            "list-ul", "list-ol", "hr", "|",
            "link", "image", "preformatted-text", "code-block", "table", "datetime", "html-entities", "|",
            "goto-line", "watch", "preview", "fullscreen",  "|",
            "help", "upimage"
        ];
    },
    toolbarIconsClass: {
        upimage: "fa-cloud-upload"  // 指定一个FontAawsome的图标类
    },
    toolbarHandlers: {
        /**
         * @param {Object}      cm         CodeMirror对象
         * @param {Object}      icon       图标按钮jQuery元素对象
         * @param {Object}      cursor     CodeMirror的光标对象，可获取光标所在行和位置
         * @param {String}      selection  编辑器选中的文本
         */
        upimage: function (cm, icon, cursor, selection) {
            // 替换选中文本，如果没有选中文本，则直接插入
            // cm.replaceSelection("[" + selection + ":testIcon]");
            // // 如果当前没有选中的文本，将光标移到要输入的位置

            //打开上传框
            uploadImgBox.find('iframe').attr('src', UPLOAD_SERVER_URL + '&from=editor&callback=callback_upload_editor');
            uploadImgBox.show();

            if (selection === "") {
                cm.setCursor(cursor.line, cursor.ch + 1);
            }
            // this == 当前editormd实例
            console.log("testIcon =>", this, cm, icon, cursor, selection);
        }
    },
    lang: {
        toolbar: {
            image : "基本图片上传",
            upimage: "可截图上传"  // 自定义按钮的提示文本，即title属性
        }
    }
});

$(".widget-content > div").css("height", (height) + 'px');
$("#catelist .category li").click(function () {
    reloadlist($(this));
    //添加文章按钮

});
//触发分类选择事件
$("#selectcat").change(function () {
    //只改变当前的文章的分类ID
    catid = parseInt($(this).val());
});
//==========================添加新文章时触发的逻辑============================
$(".add_btn").click(function () {
    if (editor.getHTML()) {
        layer.confirm('已经有一个文档在编辑,请保存!', {
            btn: ['保存', '继续编辑'], //按钮
            shade: false //不显示遮罩
        }, function () {
            if (!catid) {
                layer.msg('请选择一个文档分类', {
                    shift: 6
                });
            } else {
                var html = editor.getHTML();
                var markdown = editor.getMarkdown();
                var title = $("[name='title']").val();
                var author = $("[name='author']").val();
                var url = $("[name='url']").val();
                if (title === '') {
                    layer.msg('标题不能为空', {
                        shift: 6
                    });
                    return true;
                }
                var content = {
                    html: html,
                    markdown: markdown,
                    title: title,
                    author: author,
                    url: url,
                    catid: catid,
                    artid: artid
                };
                saveContent(content, true);
            }
            //return false;
        }, function () {
            return true;
        });
    } else {
        $("[name='title']").focus();
        return false;
    }
});
// setInterval(function () {
//     if (editor.getMarkdown()) {
//         $('.savebtn').click();
//     }
// },10 * 1000);
//============================保存====================================
$(".savebtn").click(function () {
    if (editor.getHTML()) {
        if (!parseInt(catid)) {
            layer.msg('请选择一个文档分类', {
                shift: 6
            });
        } else {
            var html = editor.getHTML();
            var markdown = editor.getMarkdown();
            var title = $("[name='title']").val();
            var author = $("[name='author']").val();
            var url = $("[name='url']").val();
            if (title === '') {
                layer.msg('标题不能为空', {
                    shift: 6
                });
                return true;
            }
            var content = {
                html: html,
                markdown: markdown,
                title: title,
                author: author,
                url: url,
                catid: catid,
                artid: artid
            };
            saveContent(content, false);
            //重新载入列表
            if (!_catid) {        //如果是首次进入页面刷新列表以新增时候选择的分类为主
                _catid = catid;
            }
            reloadlist($("#catelist li[cid='" + _catid + "']"));
        }

    } else {
        layer.msg('文档内容不能为空', {
            shift: 6
        });
    }
})


//生成PDF
$(".makepdf").click(function () {
    if (_catid === 0) {
        layer.msg('请选择要生成PDF的分类', {
            shift: 6
        });
        return false;
    }
    var loading = layer.load(1, {
        shade: [0.1, '#fff']
    });
    var _self = $(this);
    _self.html('生成中');
    $.get(MAKEPDF_URL, {catid: _catid}, function (data) {
        layer.close(loading);
        if (!parseInt(data.status)) {
            layer.msg(data.info, {shift: 6});
        } else {
            _self.html('生成PDF');
            window.location.href = data.info;
        }
    }, 'json');
});
//=========================删除按钮触发=================================
$(".delete,.delbtn").on('click', function () {
    delF($(this).parents('li').attr('aid'));
});

function delF($curid) {
    layer.confirm('是否要删除该文档!', {
        btn: ['确定删除', '取消'], //按钮
        shade: false //不显示遮罩
    }, function () {
        $.post(DELETE_ARTICLE_URL, {
            artid: $curid
        }, function (data) {
            if (data.status) {//删除文章成功
                if ($curid == artid) {  //如果删除的文档正是打开的文档就执行清空
                    editor.clear();
                    catid = 0;
                    artid = 0;  //清空当前正在编辑的文档
                    //改变当前的状态
                    $("#selectcat").val(0).change();
                    $("[name='title']").val('');
                    $("[name='url']").val('');
                }
                layer.msg(data.info, {
                    shift: 6
                });
                reloadlist($("#catelist li[cid='" + _catid + "']"));
            } else {
                layer.msg(data.info, {
                    shift: 6
                });
            }
        }, 'json');
        return true;
    }, function () {
        return true;
    });
}

function editF(obj) {
    if (obj.parents('li').attr('aid') == artid) { //阻止重复编辑
        layer.msg('您正在编辑此文档', {shift: 6});
        return true;
    }
    var _self = obj;
    if (editor.getHTML()) {
        layer.confirm('已经有一个文档在编辑,请保存!', {
            btn: ['保存', '继续编辑'], //按钮
            shade: false //不显示遮罩
        }, function () {
            if (!catid) {
                layer.msg('请选择一个文档分类', {
                    shift: 6
                });
            } else {
                var html = editor.getHTML();
                var markdown = editor.getMarkdown();
                var title = $("[name='title']").val();
                var author = $("[name='author']").val();
                var url = $("[name='url']").val();
                if (title == '') {
                    layer.msg('标题不能为空', {
                        shift: 6
                    });
                    return true;
                }
                var content = {
                    html: html,
                    markdown: markdown,
                    title: title,
                    author: author,
                    url: url,
                    catid: catid,
                    artid: artid
                };
                saveContent(content, false);
                var loading = layer.load(1, {
                    shade: [0.1, '#fff']
                });
                artid = _self.parents('li').attr('aid');
                catid = _self.parents('li').attr('catid');
                //编辑文章的catid
                $.post(GET_ARTICLE_INFO_URL, {
                    artid: artid
                }, function (data) {
                    layer.close(loading);
                    if (data.status) {
                        _self.parents('ul').find('li').css('background', '#fff');
                        _self.parents('li').css('background', '#efefef');
                        $("[name='title']").val(data.info.title);
                        $("[name='url']").val(data.info.url);
                        $("[name='author']").val(data.info.author);
                        $("#selectcat").val(data.info.cid).change();
                        editor.clear();
                        editor.setMarkdown(data.info.markdown);
                    } else {
                        layer.msg('标题不能为空', {
                            shift: 6
                        });
                    }
                }, 'json');

            }
            //return false;
        }, function () {
            return true;
        });
    } else {
        var loading = layer.load(1, {
            shade: [0.1, '#fff']
        });
        artid = _self.parents('li').attr('aid');
        $.post(GET_ARTICLE_INFO_URL, {
            artid: artid
        }, function (data) {
            layer.close(loading);
            if (data.status) {
                _self.parents('ul').find('li').css('background', '#fff');
                _self.parents('li').css('background', '#efefef');
                $("[name='title']").val(data.info.title);
                $("[name='url']").val(data.info.url);
                $("[name='author']").val(data.info.author);
                $("#selectcat").val(data.info.cid).change();
                editor.clear();
                editor.setMarkdown(data.info.markdown);
            } else {
                layer.msg('标题不能为空', {
                    shift: 6
                });
            }
        }, 'json');
        return false;
    }
}
//====================文章列表点击出发=============
$(".editbtn").click(function () {
    editF($(this));
});

$(".delcat").click(function () {
    var catid = $(this).attr('cid');
    if (catid == _catid && artid != 0) {
        layer.msg("删除的分类下还有文章正在编辑");
        return false;
    }
    var loading = layer.load(1, {
        shade: [0.1, '#fff']
    });
    $.get(DELETE_CATEGORY_URL, {
        id: catid
    }, function (data) {
        layer.close(loading);
        layer.alert(data.info);
        setTimeout(function () {
            window.location.reload();
        }, 1000);
    }, 'json');
    return false;
});

//保存编辑内容
function saveContent(content, isclear) {
    $.post(ADD_ARTICLE_URL, content, function (data) {
        if (data.status) {
            if (isclear) {
                artid = 0;
                //重置文章ID为0
                $("[name='title']").val('');
                //清空标题
                editor.clear();
                //清除编辑器内容
            } else {
                if (parseInt(data.info))
                    artid = parseInt(data.info);
            }
            layer.msg('保存内容成功', {
                icon: 1
            });
        } else {
            layer.msg('保存内容失败', {
                icon: 1
            });
        }
    }, 'json');
}

//重新加载文章列表
function reloadlist(obj) {
    var loading = layer.load(1, {
        shade: [0.1, '#fff']
    });
    _catid = obj.attr('cid');
    var catname = obj.attr('catname');
    if (typeof catname === 'undefined') {      //修复出现的BUG
        $(".showcurrcat").html("所有分类文章");
    } else {
        $(".showcurrcat").html("所有(" + catname + ")分类文章");
    }
    $.get(GET_ARTICLE_URL, {
        cid: _catid
    }, function (data) {
        layer.close(loading);
        if (data.status) {
            $("#article .category ul").empty().append(data.info);
            $(".editbtn").on('click', function () {
                editF($(this));
            });
        } else {
            layer.alert(data.info);
        }
    }, 'json');
}

function closeShowTitleBox() {
    current_titleimg_catid = 0;
    showTitleImgBox.hide();
    showTitleImgBox.find('.btn-info').unbind('click');
}

function addcat() {
    var addcate = $("#addcate");
    var catname = addcate.find('.addcat-catname').val();
    var catpid = addcate.find('select').val();
    addcate.find('.addcat-catname').val('');
    addcate.find('select').val(0).change();
    addcate.hide();
    var loading = layer.load(1, {
        shade: [0.1, '#fff']
    });
    $.get(ADD_CATEGORY_URL, {
        pid: catpid,
        catname: catname
    }, function (data) {
        layer.close(loading);
        layer.alert(data.info);
    }, 'json');
}

function callback_titleimg(catid, imgurl) {
    //更新封面图
    $.get(CATEGORY_EDIT_URL, {id: catid, imgurl: imgurl}, function (data) {
        uploadImgBox.hide();
        if (!parseInt(data.status)) {
            layer.msg(data.errmsg);
        } else {
            showTitleImgBox.find('img').attr('src', imgurl);
            $('#catid_titleimg_' + catid).attr('imgurl', imgurl);
        }
    }, 'json');
}

function callback_upload_editor(id, imgurl) {
    //主要是返回URL
    uploadImgBox.hide();
    editor.insertValue('![new image](' + imgurl + ')');
}

var cacheTimer = null;
//开启本地存储 根据当前文章ID存储
function localCache() {

}